<?php
/**
 * @Name: RoleServices.php
 * @Author: yashuai<1762910894@qq.com>
 */

namespace app\common\services\rbac;

use app\common\logic\rbac\RoleLogic;
use app\common\services\BaseServices;
use HugCode\PhpUnits\Frame\Code\ConstCode;

class RoleServices extends BaseServices
{

    public function __construct(RoleLogic $logic)
    {
        $this->logic = $logic;
    }

    /**
     * @Desc 列表
     * @return array
     * @author yashuai<1762910894@qq.com>
     */
    public function getList(array $params = [])
    {
        $where  = [
            'RoleStatus' => _array_field($params, 'Status', ConstCode::BASIC_STATUS_NORMAL)
        ];
        $result = $this->getPageList($where, ['*'], ['node', 'node.node']);

        $childrenMap = [];
        if (!empty($result['list'])) {
            foreach ($result['list'] as $item) {
                foreach ($item['node'] as $info) {
                    if (is_array($info)) {
                        $childrenMap[$info['node']['ParentID']] = $info['node']['NodeID'];
                    }
                }
            }
            foreach ($result['list'] as &$val) {
                $nodeList = [];
                foreach ($val['node'] as $node) {
                    if (!isset($childrenMap[$node['NodeID']])) {
                        $nodeList[] = $node['NodeID'];
                    }
                }
                $val['NodeID'] = $nodeList;
                unset($val['node']);
            }
        }
        return $result;
    }

    /**
     * @Desc 角色设置菜单节点
     * @param array $params
     * @return bool
     * @author yashuai<1762910894@qq.com>
     */
    public function node(array $params)
    {
        $info = $this->get($params['RoleID'], ['RoleID', 'RoleStatus']);
        if (empty($info) || $info['RoleStatus'] != ConstCode::BASIC_STATUS_NORMAL) {
            _throw('', 106001);
        }

        /** @var NodeServices $nodeService */
        $nodeService = app()->make(NodeServices::class);
        $node        = $nodeService->selectList(['NodeID' => $params['NodeID']], ['NodeID'])->toArray();
        $node        = array_column($node, 'NodeID');
        if (empty($node)) {
            _throw('菜单节点不存在', 106001);
        }
        $data = [];
        foreach ($node as $nodeID) {
            $data[] = [
                'RoleID' => $params['RoleID'],
                'NodeID' => $nodeID,
            ];
        }
        /** @var RoleNodeServices $roleNodeService */
        $roleNodeService = app()->make(RoleNodeServices::class);
        $roleNodeService->physicalDeleteRow(['RoleID' => $params['RoleID']]);
        $roleNodeService->createRowAll($data);
        return true;
    }

}
